#import <BCComConfigKit/BCComConfig.h>
#import <BCFoundation/BCFoundation.h>
#import <BCUIKit/BCUIKit.h>
#import <Masonry/Masonry.h>
#import "HHAlertController.h"
#import "HHAlertControllerAnimated.h"

@interface HHAlertController ()<HHAlertAnimatedController>

@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UILabel *descLab;

@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UIButton *otherBtn;

@property (nonatomic, strong) NSString *cancelBtnTitle;
@property (nonatomic, strong) NSString *otherBtnTitle;

/// 选择回调
@property (nonatomic, copy, nullable) void (^ selectedBlock)(NSInteger index);
@end

@implementation HHAlertController
@synthesize alertView = _alertView;

///MARK: - system
- (instancetype)init {
    self = [super init];

    if (self) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.transitioningDelegate = (id<UIViewControllerTransitioningDelegate>)self;
    }

    return self;
}

///MARK: - public
+ (HHAlertController *)showTitle:(nullable NSString *)title message:(nullable NSString *)message completion:(void (^_Nullable)(NSInteger index))completion {
    return [self showTitle:title message:message cancelTitle:@"取消" otherTitle:@"确定" completion:completion];
}

+ (HHAlertController *)showTitle:(nullable NSString *)title message:(nullable NSString *)message cancelTitle:(nullable NSString *)cancelTitle otherTitle:(nullable NSString *)otherTitle completion:(void (^_Nullable)(NSInteger index))completion {
    HHAlertController *alertController = [[HHAlertController alloc] init];

    if (title) {
        alertController.title = title;
    }

    if (message) {
        alertController.message = message;
    }

    alertController.cancelBtnTitle = cancelTitle;
    alertController.otherBtnTitle = otherTitle;
    alertController.selectedBlock = completion;


    UIViewController *topPage = [UIApplication sharedApplication].keyWindow.rootViewController;
    [topPage presentViewController:alertController animated:YES completion:NULL];

    return alertController;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initializePageSubviews];
}

//MARK: - setter
- (void)setMessage:(NSString *)message {
    _message = message;

    self.descLab.attributedText = [[NSAttributedString alloc] initWithString:message attributes:self.messageAttributes];
}

- (void)setCancelBtnTitle:(NSString *)cancelBtnTitle {
    _cancelBtnTitle = cancelBtnTitle;
    [self.cancelBtn setTitle:cancelBtnTitle forState:UIControlStateNormal];
}

- (void)setOtherBtnTitle:(NSString *)otherBtnTitle {
    _otherBtnTitle = otherBtnTitle;
    [self.otherBtn setTitle:otherBtnTitle forState:UIControlStateNormal];
}

//MARK: - butten respone
- (void)cancelButtonClicked:(id)sender {
    if(self.selectedBlock){
        self.selectedBlock(0);
    }
    [self dismissSelfPage];
}

- (void)otherButtonClicked:(id)sender {
    if(self.selectedBlock){
        self.selectedBlock(1);
    }
    [self dismissSelfPage];
}
///MARK: - private
- (void)dismissSelfPage {
    [self dismissViewControllerAnimated:YES completion:NULL];
}
///MARK: - Page subviews
- (void)reloadContentLayout {
    if (!self.alertView.superview) {
        return;
    }

    CGFloat contentHeight = 15;

    if (self.title.length > 1) {
        contentHeight += 50;
    }

    if (self.message) {
        CGFloat msgHeight = [self.message boundingRectWithSize:CGSizeMake(kBCWidth(270) - 32, MAXFLOAT)
                                                       options:NSStringDrawingUsesLineFragmentOrigin
                                                    attributes:self.messageAttributes
                                                       context:nil].size.height;
        contentHeight += msgHeight;
    }

    contentHeight += 30;

    if (self.cancelBtnTitle || self.otherBtnTitle) {
        contentHeight += 44;
    }

// 设定最大值不超过屏幕-160
    contentHeight = MIN(kBCSCREEN_HEIGHT - 88, contentHeight);

    // Constraints
    [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view);
        make.width.mas_equalTo(kBCWidth(270));
        make.height.mas_equalTo(contentHeight);
    }];

    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.alertView);
        make.top.mas_equalTo(15);
        make.height.mas_equalTo(50);
    }];
    CGFloat descTop = self.title.length > 1 ? 65 : 15;
    [_descLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.top.mas_equalTo(descTop);
    }];

    NSMutableArray *mBtnArr = [[NSMutableArray alloc] init];

    if (self.cancelBtnTitle) {
        [mBtnArr addObject:self.cancelBtn];
        [self.alertView addSubview:self.cancelBtn];
    }

    if (self.otherBtnTitle) {
        [mBtnArr addObject:self.otherBtn];
        [self.alertView addSubview:self.otherBtn];
    }

    if (mBtnArr.count > 0) {
        [mBtnArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:1 leadSpacing:0 tailSpacing:0];
        [mBtnArr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.alertView);
            make.height.mas_equalTo(44);
        }];

        // separator
        UIImageView *hSeparatorView = [[UIImageView alloc] init];
        hSeparatorView.backgroundColor = [UIColor bc_colorWithRGB:0xD8D8D8];
        [self.alertView addSubview:hSeparatorView];
        [hSeparatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-45);
            make.left.right.mas_equalTo(self.alertView);
            make.height.mas_equalTo(0.6f);
        }];

        if (mBtnArr.count > 1) {
            UIButton *firstBtn = mBtnArr.firstObject;
            UIImageView *vSeparatorView = [[UIImageView alloc] init];
            vSeparatorView.backgroundColor = [UIColor bc_colorWithRGB:0xD8D8D8];
            [self.alertView addSubview:vSeparatorView];
            [vSeparatorView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(hSeparatorView.mas_bottom);
                make.bottom.mas_equalTo(self.alertView);
                make.left.mas_equalTo(firstBtn.mas_right);
                make.width.mas_equalTo(0.6f);
            }];
        }
    }
}

- (void)initializePageSubviews {
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];

    // 整体内容view
    [self.view addSubview:self.alertView];
    [self.alertView addSubview:self.titleLab];
    [self.alertView addSubview:self.descLab];

    self.titleLab.text = self.title;

    [self reloadContentLayout];
}

//MARK: - helper
- (NSDictionary *)messageAttributes {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    paragraphStyle.lineSpacing = 6;

    return @{
        NSFontAttributeName: BCComConfig.config.bcFont(16),
        NSParagraphStyleAttributeName: paragraphStyle,
        NSForegroundColorAttributeName: BCComConfig.config.blackColor
    };
}

//MARK: - getter
- (UIView *)alertView {
    if (!_alertView) {
        _alertView = [[UIView alloc] init];
        _alertView.layer.masksToBounds = YES;
        _alertView.layer.cornerRadius = 12.f;
        _alertView.clipsToBounds = YES;
        _alertView.backgroundColor = [UIColor whiteColor];
    }

    return _alertView;
}

- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.font = BCComConfig.config.bcBoldFont(16);
        _titleLab.textColor = [UIColor bc_colorWithRGB:0x1B1B1B];
        _titleLab.textAlignment = NSTextAlignmentCenter;
        _titleLab.numberOfLines = 0;
        _descLab.preferredMaxLayoutWidth = kBCWidth(270) - 42;
    }

    return _titleLab;
}

- (UILabel *)descLab {
    if (!_descLab) {
        _descLab = [[UILabel alloc] init];
        _descLab.font = BCComConfig.config.bcFont(16);
        _descLab.textColor = BCComConfig.config.blackColor;
        _descLab.numberOfLines = 0;
        _descLab.preferredMaxLayoutWidth = kBCWidth(270) - 32;
    }

    return _descLab;
}

- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.titleLabel.font = BCComConfig.config.bcBoldFont(16);
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor bc_colorWithRGB:0x1B1B1B] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }

    return _cancelBtn;
}

- (UIButton *)otherBtn {
    if (!_otherBtn) {
        _otherBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _otherBtn.titleLabel.font = BCComConfig.config.bcBoldFont(16);
        [_otherBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_otherBtn setTitleColor:BCComConfig.config.defaultColor forState:UIControlStateNormal];
        [_otherBtn addTarget:self action:@selector(otherButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }

    return _otherBtn;
}

//MARK: - UIViewControllerAnimatedTransitioning
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[HHAlertControllerAnimated alloc]init];
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [[HHAlertControllerAnimated alloc]init];
}

@end
